package com.company;

import java.util.Scanner;

public class Main {

    //String s="the sky is blue";

    public static String reverseWords(String s) {
        StringBuilder sb=removeSpace(s);
        reverseString(sb,0,sb.length()-1);
        reverseEach(sb);
        System.out.println(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        String s="   the sky is blue   ";
        String s1=reverseWords(s);
    }

    public static StringBuilder removeSpace(String s) {
        int start=0,end=s.length()-1;
        while(s.charAt(start)==' ') start++;
        while(s.charAt(end)==' ') end--;
        StringBuilder sb=new StringBuilder();
        while(start<=end)
        {
            char c=s.charAt(start);
            if(c!=' '|| sb.charAt(sb.length() - 1) != ' ')
            {
                sb.append(c);
            }
            start++;
        }
        return sb;
    }

    public static void reverseString(StringBuilder sb,int start,int end){
        while(start<end)
        {
            char temp=sb.charAt(start);
            sb.setCharAt(start,sb.charAt(end));
            sb.setCharAt(end,temp);
            start++;
            end--;
        }
    }

    public static void reverseEach(StringBuilder sb){
        int start=0,end=1,n=sb.length();
        while (start<n)
        {
            while(end<n&&sb.charAt(end)!=' ')
            {
                end++;
            }
            reverseString(sb,start,end-1);
            start=end+1;
            end=start+1;
        }
    }
}

